<?php
/*
 * Author  : top-songshijie
 * Email   : 997031758@qq.com
 * DateTime: 2023/03/20 11:20
 */

namespace SSJ\LaravelHelper\Services\Upload\Strategy;

use Qiniu\Auth;
use Qiniu\Storage\UploadManager;
use Illuminate\Support\Facades\Storage;
use SSJ\LaravelHelper\Models\Attachment;
use SSJ\LaravelHelper\Services\Upload\Strategy;

class QiniuStrategy extends Strategy
{
    public function handle()
    {
        $attachment = Attachment::check($this->data['md5'], $this->data['sha1']);
        if (lh_isset_not_empty($attachment, 'alioss_preview_path')) {
            return $attachment;
        }

        $this->data['qiniu_preview_path'] = $this->upload($this->file, $this->data['path']);

        if ($attachment) {
            $attachment->update(['qiniu_preview_path' => $this->data['qiniu_preview_path']]);
        } else {
            $attachment = Attachment::query()->create($this->data);
        }

        return $attachment;
    }

    /**
     * 上传到七牛云
     *
     * @param $file
     * @param $filename
     *
     * @return string
     */
    public function upload($file, $filename)
    {
        $uploadMgr = new UploadManager();

        $auth  = new Auth(config('qiniu.access_key'), config('qiniu.secret_key'));
        $token = $auth->uploadToken(config('qiniu.bucket'));

        list($res, $error) = $uploadMgr->putFile($token, $filename, $file);

        return config('qiniu.domain') . '/' . $res['key'];
    }
}
